package com.sy.simpleegg.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.DialogInterface
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.sy.simpleegg.R
import com.sy.simpleegg.adapter.PayTypeYchAdapter
import com.sy.simpleegg.bean.GoodBean
import com.sy.simpleegg.bean.PayTypeDataYch
import com.sy.simpleegg.databinding.DialogKkbPayBinding
import com.sy.simpleegg.ext.countDown
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.util.QRCodeUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel


class KkbPayDialog(
    private val title: String?,
    private val tips: String?,
    private val payTypeList: MutableList<PayTypeDataYch>,
    private val goodBean: GoodBean,
    private val countDownTime: Int,
    private var payTypeDialogListener: PayTypeDialogListener,
): DialogFragment() {

    private lateinit var binding: DialogKkbPayBinding

    var timeDownScope: CoroutineScope? = null

    private var payType = ""

    private var transId = goodBean.k

    override fun onStart() {
        super.onStart()
//        dialog!!.window!!.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)

        val width = resources.getDimensionPixelSize(R.dimen.dialog_paytype_width)
        val height = resources.getDimensionPixelSize(R.dimen.dialog_ych_pay_type_height)
//        val marginBottom = resources.getDimensionPixelSize(R.dimen.dialog_good_detail_margin_bottom)

//        dialog!!.window!!.setLayout(width, height + marginBottom)
        dialog!!.window!!.setLayout(width, height)
        dialog!!.window!!.setGravity(Gravity.CENTER)
        dialog!!.setCanceledOnTouchOutside(false)
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?,
    ): View? {
        binding = DialogKkbPayBinding.inflate(inflater, container, false)
//        setStyle(STYLE_NO_TITLE, R.style.MyDialog)
//        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT))
//        dialog!!.window!!.setGravity(Gravity.BOTTOM)
        dialog!!.window!!.setBackgroundDrawableResource(R.color.transparent)
//        var wlp = dialog!!.window!!.attributes
//        wlp.gravity = Gravity.BOTTOM
//        wlp.width = WindowManager.LayoutParams.MATCH_PARENT
//        wlp.height = WindowManager.LayoutParams.MATCH_PARENT
//        dialog!!.window!!.attributes = wlp

        return binding.root
    }

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        try {
            binding.layoutClose.tvDismiss.text = "${countDownTime}S"

            binding.layoutClose.tvClose.setOnClickListener {
                payTypeDialogListener.back()
                dismissAllowingStateLoss()
            }
            binding.btnDismiss.setOnClickListener {
                payTypeDialogListener.back()
                dismissAllowingStateLoss()
            }

            binding.rvPayType.layoutManager = GridLayoutManager(requireContext(), 3)
            binding.rvPayType.adapter = PayTypeYchAdapter(requireContext(), payTypeList).apply { setOnItemClickListener(object : PayTypeYchAdapter.OnItemClickListener{
                override fun onClick(payTypaData: PayTypeDataYch?) {
                    payTypaData?.let {
                        payType = it.codeName
                        payTypeDialogListener.selectPayType(it, goodBean)
                        resetCountDown()
                    }
                }
            }) }

            homePage()
        }catch (e: Exception){
            e.printStackTrace()
            logFile("初始化页面异常：${e.message}")
        }
    }

    override fun showNow(manager: FragmentManager, tag: String?) {
        super.showNow(manager, tag)
        startCountDown(countDownTime)
    }

    override fun show(manager: FragmentManager, tag: String?) {
        super.show(manager, tag)
        startCountDown(countDownTime)
    }

    override fun show(transaction: FragmentTransaction, tag: String?): Int {
        val result = super.show(transaction, tag)
        startCountDown(countDownTime)
        return result

    }

    override fun onDismiss(dialog: DialogInterface) {
        super.onDismiss(dialog)
        payTypeDialogListener.dismiss(transId)
    }

    @SuppressLint("SetTextI18n")
    private fun startCountDown(timeout: Int){
//        var timeDownScope: CoroutineScope? = null
        timeDownScope?.cancel()

        countDown(
            time = countDownTime,
            start = {
                timeDownScope = it
                logFile("开始倒计时")
            },
            end = {
                logFile("结束倒计时")
            },
            next = {
                binding.layoutClose.tvDismiss.text = "${it}S"
                if (it == 0){
                    dismissAllowingStateLoss()
                }
            })
    }

    /**
     * 刷新二维码
     * @param qrCode 二维码数据
     */
    fun refreshQrCode(qrCode: String){
        try {
            if (qrCode.isEmpty()){
                binding.pbQrCode.visibility = View.VISIBLE
                binding.ivQrCode.visibility = View.GONE
                return
            }
            binding.pbQrCode.visibility = View.GONE
            Glide.with(binding.root)
                .load(QRCodeUtil.createQRCode(qrCode, 500, 500))
                .fitCenter()
                .into(binding.ivQrCode)
            binding.ivQrCode.visibility = View.VISIBLE
            startCountDown(countDownTime)
        }catch (e: Exception){
            e.printStackTrace()
            logFile("刷新二维码异常：${e.message}")
        }
    }


    /**
     * 支付状态
     * @param status 0-支付中 1-支付完成 2-支付异常
     */
    fun setPayStatus(orderId: String, status: Int){
        transId = orderId
        when (status){
            0 -> {
                payingPage()
                resetCountDown()
            }
            1 -> {
                paySuccessedPage()
            }
            2 -> {
                payFailedPage()
                startCountDown(5)
            }
        }
    }

    /**
     * 默认页面
     */
    private fun homePage(){
        binding.tvTitle.text = title
        binding.tvTips.text = tips
        binding.llCodeAndPayType.visibility = View.VISIBLE
        binding.rlPayStatus.visibility = View.GONE
        payTypeList.forEach { payTypeItem ->
            if (payTypeItem.isSelected){
                payType = payTypeItem.codeName
            }
        }
    }

    /**
     * 支付中
     */
    private fun payingPage(){
        binding.llCodeAndPayType.visibility = View.GONE
        binding.rlPayStatus.visibility = View.VISIBLE
        binding.tvPayStatus.text = getString(R.string.paying)
        loadPayStatusPic(R.mipmap.ic_paying)
    }

    /**
     * 支付成功
     */
    private fun paySuccessedPage(){
        binding.llCodeAndPayType.visibility = View.GONE
        binding.rlPayStatus.visibility = View.VISIBLE
        binding.tvPayStatus.text = getString(R.string.pay_successed)
        loadPayStatusPic(R.mipmap.ic_pay_successed)
    }

    /**
     * 支付异常
     */
    private fun payFailedPage(){
        binding.llCodeAndPayType.visibility = View.GONE
        binding.rlPayStatus.visibility = View.VISIBLE
        binding.tvPayStatus.text = getString(R.string.pay_failed)
        loadPayStatusPic(R.mipmap.ic_pay_failed)
    }

    private fun loadPayStatusPic(resId: Int){
        Glide.with(requireContext())
            .load(resId)
            .fitCenter()
            .into(binding.ivPayStatus)
    }

    fun getPayType(): String{
        resetCountDown()
        return payType
    }

    fun getSelectedGood(): GoodBean{
        return goodBean
    }

    private fun resetCountDown(){
        startCountDown(countDownTime)
    }

    interface PayTypeDialogListener{
        fun dismiss(transId: String)

        fun back()

        fun selectPayType(payTypeData: PayTypeDataYch, goodBean: GoodBean)
    }

    fun dpToPx(context: Context, dp: Int): Int {
        val density = context.resources.displayMetrics.density
        return Math.round(dp * density)
    }
}